# 采用 pandas操作 操作数据，
# 使用决策树（由于决策树不支持字符集）


from sklearn.tree import DecisionTreeClassifier
from sklearn import tree
from sklearn.model_selection import train_test_split
import numpy as np
from sklearn import metrics
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
import pandas as pd
### 加载数据集 ######################
import pandas
df = pandas.read_csv('melon2.0.csv')
print(df)
print(df.columns)

for i in range(1, 7):
    col = df.columns[i]
    df[col] = pd.Categorical(df[col]).codes


df = df.values
y_data = df[:, -1]
x_data = df[:, 1:-1]
print(x_data.shape, y_data.shape)
print(x_data, y_data)


# np.random.seed(2022)  # 固定随机种子  数量太少就不划分 训练集与测试集
# x_train, x_test, y_train, y_test = train_test_split(x_data, y_data, test_size=0.3)  # 随机抽取30%的测试集

### 建立决策树  ##############
clf = DecisionTreeClassifier(criterion="entropy")  # 采用信息熵 ID3算法
clf.fit(x_data, y_data)
tree.plot_tree(clf)

# 把树形结构输出到pdf
# !pip install graphviz
import graphviz
from sklearn import tree
dot_data = tree.export_graphviz(clf, out_file=None)
graph = graphviz.Source(dot_data)
graph.render("西瓜2.0数据集") # 生成 '决策树.pdf'


### 输出结果  ###############
score = clf.score(x_data, y_data)#输出训练误差
print(score)
plt.show()





## 以文字结构输出 树形结构
# from sklearn.tree import export_text
# r = export_text(clf, feature_names=iris['feature_names'])
# print(r)

